package com.mini.demos.webgame.queue;

import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import com.mini.demos.webgame.db.JobService;
import com.mini.demos.webgame.entity.Job;
import com.mini.demos.webgame.msg.JobMsg;
import com.mini.demos.webgame.util.JobStatEnum;

public class JobQueue {
	
	private Map<Integer,JobMsg> jobMap= new ConcurrentHashMap<Integer,JobMsg>();;
	
	private static JobQueue instance = new JobQueue();
	
	
	private Timer timer = new Timer();
	
	private static Logger log = Logger.getLogger("JobQueue");
	
	
	
	public static JobQueue getInstance(){
		return instance;
	}
	
	public void addJob(JobMsg jobMsg){
		log.info("add job,id:" +jobMsg.getJobId());
		synchronized(jobMap){
			if(jobMap.containsKey(jobMsg.getJobId())){
				return;
			}
			this.jobMap.put(jobMsg.getJobId(),jobMsg);
		}
		
		log.info("add job after,size:" +jobMap.size());
		Long time = jobMsg.getCostTime().longValue() *60 * 60 * 1000;
		Worker worker = new Worker(jobMsg);
		timer.schedule(worker, time);
	}
	
	public boolean isExitUserTypeJob(String userName,Integer type){
		synchronized(jobMap){
			log.info("isExitUserTypeJob job list:" +this.jobMap.size());
			Collection<JobMsg> jobs = jobMap.values();
			for(JobMsg job:jobs){
				log.info("-------");
				log.info(job.getUserName());
				log.info(job.getJobType().toString());
				log.info("-------");
				if(job.getUserName().equals(userName) && job.getJobType().intValue()==type.intValue()){
					return true;
				}
			}
			return false;
		}
	}
	
	
	class Worker extends TimerTask{
		private JobMsg jobMsg;
		Worker(JobMsg jobMsg){
			this.jobMsg = jobMsg;
		}
		public void run(){
			try{
				log.info("start job,id:"+jobMsg.getJobId());
				JobService jobService = new JobService();
				Job job = jobService.getJob(jobMsg.getJobId().longValue());
				synchronized(job){
					Date now = new Date();
					job.setModifyDate(now);
					job.setState(JobStatEnum.HARVEST.getStatCode());
					jobService.update(job);
				}
				System.out.println("session is closeed:"+jobMsg.getSender().isSessionClose());
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
	}
	
	public static void main(String arg[]){
		
	}

}
